package com.du.javaweb.filter; /**
 * @author : DuJiabao
 * @Date : 2021/3/28 19:00
 * @Project : java-web
 * @File : ${FILE_NAME}
 * @Desc :
 */

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Enumeration;

//@WebFilter(filterName = "AdminFilter", urlPatterns = "/admin/*")
public class AdminFilter implements Filter {
  public AdminFilter() {
    System.out.println("这是AdminFilter的构造方法");
  }

  public void init(FilterConfig config) throws ServletException {
    System.out.println("这是AdminFilter的init()方法");
    // 获取过滤器的名字
    String filterName = config.getFilterName();
    System.out.println(filterName);
    // 获取servletContext对象
    ServletContext servletContext = config.getServletContext();
    System.out.println(servletContext);
    System.out.println(servletContext.getInitParameter("context_param"));
    // 获取初始化参数的值
    String param = config.getInitParameter("param");
    System.out.println(param);
    // 获取所有初始化参数的名字
    Enumeration<String> initParameterNames = config.getInitParameterNames();
    while (initParameterNames.hasMoreElements()) {
      System.out.println(initParameterNames.nextElement());
    }
  }

  public void destroy() {
    System.out.println("这是AdminFilter的destroy()方法");
  }

  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
    HttpServletRequest httpServletRequest = (HttpServletRequest) request;
    HttpSession session = httpServletRequest.getSession();
    // 判断是否有已经登录的记录
    Object user = session.getAttribute("user");
    if (user == null) {
      request.getRequestDispatcher("/login.jsp").forward(request, response);
      return;
    }
    chain.doFilter(request, response);
  }
}
